<template>
  <div class="addComponent-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>诱导发布</el-breadcrumb-item>
      <el-breadcrumb-item>设备管理</el-breadcrumb-item>
      <el-breadcrumb-item>诱导屏配置屏显</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="add-component">
      <div class="title">配置【{{ list.name }}】屏显</div>
      <div v-for="(detail, index) in details" :key="index">
        <div class="row content">
          <div>显示明细{{ index + 1 }}</div>
          <div>
            <el-button
              v-if="details.length > 1"
              class="reset-btn"
              @click="removeDetail(detail)"
              >删除明细</el-button
            >
            <el-button class="confirm-btn" @click="addDetail()">添加明细</el-button>
          </div>
        </div>
        <div class="add-form">
          <el-form
            ref="detailFormRefs"
            :rules="rules"
            :model="detail"
            label-width="120"
            label-position="top"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="X坐标" prop="xaxis">
                  <el-input
                    v-model="detail.xaxis"
                    style="width: 294px"
                    placeholder="请输入X坐标"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="Y坐标" prop="yaxis">
                  <el-input
                    v-model="detail.yaxis"
                    style="width: 294px"
                    placeholder="请输入Y坐标"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="显示内容" prop="type">
                  <el-select
                    v-model="detail.type"
                    filterable
                    style="width: 294px"
                    placeholder="请选择显示内容"
                    @change="changeType"
                  >
                    <el-option
                      v-for="item in type.data"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 当显示内容 type = 1 || 2 || 3 -->
            <div v-if="detail.type === 1 || detail.type === 2 || detail.type === 3">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="字号" prop="wordSize" ref="">
                    <el-input
                      v-model="detail.wordSize"
                      style="width: 294px"
                      placeholder="请输入字号"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="字色" prop="wordColor">
                    <el-select
                      v-model="detail.wordColor"
                      filterable
                      style="width: 294px"
                      placeholder="请选择字色"
                    >
                      <el-option
                        v-for="item in wordColor.data"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="水平对齐方式" prop="horizontal">
                    <el-select
                      v-model="detail.horizontal"
                      filterable
                      style="width: 294px"
                      placeholder="请选择水平对齐方式"
                    >
                      <el-option
                        v-for="item in horizontal.data"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="垂直对齐方式" prop="vertical">
                    <el-select
                      v-model="detail.vertical"
                      filterable
                      style="width: 294px"
                      placeholder="请选择垂直对齐方式"
                    >
                      <el-option
                        v-for="item in vertical.data"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="detail.type !== 3">
                  <el-form-item label="路段关联/停车场" prop="sections" class="sections">
                    <template #label>
                      <div>路段关联/停车场</div>
                      <el-button @click="getSection(index)">关联</el-button>
                    </template>
                    <el-input
                      disabled
                      v-model="detail.sectionsName"
                      style="width: 294px"
                      placeholder="请点击关联"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8" v-if="detail.type === 3">
                  <el-form-item label="展示文字" prop="text">
                    <el-input
                      v-model="detail.text"
                      style="width: 294px"
                      placeholder="请输入展示文字"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 当显示内容 type = 4 -->
            <div v-if="detail.type === 4">
              <el-form-item
                label="展示图片(仅上传一张)"
                prop="fileId"
                @click="dangqian(index)"
              >
                <!-- <el-upload
                    :file-list="detail.image"
                    action="*"
                    list-type="text"
                    :limit="1"
                    size="small"
                    :show-file-list="true"
                    :before-upload="beforeAvatarUpload"
                    :on-change="fileListUpLoad"
                    :on-success="handleAvatarSuccess"
                    :disabled="disable"
                  >
                    <el-button type="primary" @click="goUpload(index)">上传</el-button>
                  </el-upload> -->

                <!-- <el-upload
                    class="avatar-uploader"
                    action="*"
                    list-type="picture-card"
                    :limit="1"
                    :show-file-list="false"
                    :on-change="fileListUpLoad"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="detail.fileUrl" :src="detail.fileUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload> -->
                <el-upload
                  action="#"
                  v-model:file-list="fileList[index]"
                  :on-change="fileListUpLoad"
                  :limit="1"
                  :disabled="fileList[index].length != 0"
                  list-type="picture-card"
                  :auto-upload="false"
                >
                  <el-icon><Plus /></el-icon>

                  <template #file="{ file }">
                    <div>
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(index)"
                        >
                          <el-icon><zoom-in /></el-icon>
                        </span>

                        <span
                          class="el-upload-list__item-delete"
                          @click="handleRemove(index)"
                        >
                          <el-icon><Delete /></el-icon>
                        </span>
                      </span>
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="footer">
        <div></div>
        <div>
          <el-button class="reset-btn" @click="resetForm()">取 消</el-button>
          <el-button class="confirm-btn" @click="submitForm()">确 认</el-button>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible2">
      <img w-full :src="dialogImageUrl" width="600px" height="auto" alt="Preview Image" />
    </el-dialog>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      destroy-on-close
      :before-close="handleClose"
      :close-on-click-modal="false"
      :width="670"
    >
      <component
        :is="componentTag"
        @operationDone="operationDone"
        :operationId="operationId"
        :leftChecks="leftChecks"
      >
      </component>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, shallowRef } from "vue";
import { getDictionary, getRoadList } from "@/service/modules/publicModule";
import associatedDevicesComponent from "../components/associatedDevicesComponent.vue";

import { Plus, Delete, ZoomIn } from "@element-plus/icons-vue";
import { getAddGuideShow, getGuideShowDetails, getUpload } from "../request.js";

import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

// 弹窗
const title = ref("");
//当前index
const dqindex = ref(0);
const dialogVisible = ref(false);
const componentTag = shallowRef("");
const operationId = ref();
const leftChecks = ref([]);
const operationDone = (r) => {
  dialogVisible.value = false;
  operationId.value = "";
  if (!r) {
    // getData();
    //
  } else {
    console.log("r ===>", r.selectValue);
    details.value[dqindex.value].sections = r.selectValue;
    let names = [];
    for (let n = 0; n < r.selectValue.length; n++) {
      let name = getDateName(table.data, r.selectValue[n]);
      names.push(name);
    }
    details.value[dqindex.value].sectionsName = names;
  }
};

const detailFormRefs = ref({});
const detailForm = reactive({
  data: [],
});

const type = reactive({
  data: [],
});

const wordColor = reactive({
  data: [],
});

const horizontal = reactive({
  data: [],
});
const vertical = reactive({
  data: [],
});
const table = reactive({
  data: [],
});
const getData = async () => {
  await getDictionary("screen_show_type").then((res) => {
    type.data = res.data.result;
  });
  await getDictionary("screen_word_color").then((res) => {
    wordColor.data = res.data.result;
  });
  await getDictionary("horizontal_align").then((res) => {
    horizontal.data = res.data.result;
  });
  await getDictionary("vertical_align").then((res) => {
    vertical.data = res.data.result;
  });
};
getData();

const changeType = (val) => {
  console.log("val ===>", val);
};

// 路段关联/停车场
const getSection = (value) => {
  title.value = `配置【${list.value.name}】`;
  dqindex.value = value;
  leftChecks.value = details.value[value].sections;
  console.log("value ===>", leftChecks.value);
  componentTag.value = associatedDevicesComponent;
  operationId.value = value;
  dialogVisible.value = true;
};

const setDetail = () => {
  let flag = 0;
  let len;
  try {
    len = details.value.length;
  } catch (e) {
    len = 0;
  }
  for (let i = 0; i < len; i++) {
    if (details.value[i].index === i) {
      flag++;
    }
  }
  return {
    index: flag,
  };
};
const fileList = ref([]);
fileList.value.push([]);
console.log(fileList.value[0], ">>>>>>>>>");
// 添加明细
const details = ref([setDetail()]);
const addDetail = () => {
  fileList.value.push([]);
  console.log(fileList.value, ">>>>>>>>>");
  details.value.push(setDetail());
  details.value.sort((a, b) => a.index - b.index);
};

// 删除明细
const removeDetail = (pointer) => {
  const index = details.value.findIndex((item) => item === pointer);

  if (details.value.length > 1) {
    // 确保至少有两个明细
    fileList.value.splice(index, 1);
    details.value.splice(index, 1); // 删除指定索引的明细
  }
};

const rules = reactive({
  xaxis: [{ required: true, message: "请输入X坐标", trigger: "blur" }],
  yaxis: [{ required: true, message: "请输入Y坐标", trigger: "blur" }],
  type: [{ required: true, message: "请选择显示内容", trigger: "change" }],
  wordSize: [{ required: true, message: "请输入字号", trigger: "blur" }],
  wordColor: [{ required: true, message: "请选择字色", trigger: "change" }],
  horizontal: [{ required: true, message: "请选择水平对齐方式", trigger: "change" }],
  vertical: [{ required: true, message: "请选择垂直对齐方式", trigger: "change" }],
  sections: [{ required: true, message: "请点击关联", trigger: "change" }],
  text: [{ required: true, message: "请输入展示文字", trigger: "blur" }],
  fileId: [{ required: true, message: "请上传图片", trigger: "blur" }],
});

// 上传图片
const upliadIndex = ref("");
const goUpload = (index) => {
  console.log("index ===>", index);
  upliadIndex.value = index;
};
const dangqian = (index) => {
  dqindex.value = index;
};
const disable = ref(false);
const beforeAvatarUpload = (file) => {
  console.log("11 ===>", file);
  return new Promise(async (resolve, reject) => {
    // console.log(file);
    // 验证文件大小
    if (
      file.type !== "image/jpeg" &&
      file.type !== "image/png" &&
      file.type !== "image/jpg"
    ) {
      ElMessage.error("所上传图片类型不支持");
      reject();
    } else if (file.size / 1024 > 100) {
      ElMessage.error("所上传图片不能超过100KB");
      reject();
    }
  });
};

const fileListUpLoad = (uploadFile) => {
  const fileSize = uploadFile.size / 1024;
  const file = uploadFile.raw;
  console.log(fileSize, ">>>>>>>>>>.");
  if (
    file.type !== "image/jpeg" &&
    file.type !== "image/png" &&
    file.type !== "image/jpg"
  ) {
    ElMessage.error("所上传图片类型不支持");
    fileList.value[dqindex.value] = [];
    reject();
  } else if (fileSize > 100) {
    ElMessage.error("所上传图片不能超过100KB");
    fileList.value[dqindex.value] = [];
    reject();
  } else {
    getUpload({
      file: uploadFile.raw,
      fileType: "img",
      bucket: "cipp-road-park-img",
      tags: "诱导屏设备参数上传图片",
    }).then((res) => {
      details.value[dqindex.value].fileId = res.data.result.id;
      details.value[dqindex.value].fileUrl =
        // "https://cippfile.ecaray.com/" +
        res.data.result.bucket + "/" + res.data.result.filePath;
      console.log(fileList.value, ">>>>>>>>");
      // fileList.value[dqindex.value].push({
      //   name: details.value[dqindex.value].fileId,
      //   url: details.value[dqindex.value].fileUrl,
      // });
    });
  }
  // if (fileSize < 100) {

  // } else {
  //   return false;
  // }
};
const dialogImageUrl = ref("");
const dialogVisible2 = ref(false);
const disabled = ref(false);

const handleRemove = (index) => {
  fileList.value[index] = "";
};

const handlePictureCardPreview = (index) => {
  dialogImageUrl.value = fileList.value[index][0].url;
  dialogVisible2.value = true;
};

// 表单提交
const submitForm = async (formEl) => {
  // console.log("formEl ===>", detailFormRefs);

  try {
    // 等待所有表单校验完成
    const isValid = await validateForms();
    if (isValid) {
      console.log("所有表单校验通过");
      details.value.forEach((item) => {
        // console.log("item ===>", item);
        item.deviceId = list.value.id;
      });

      // console.log("details.value ===>", details.value);
      // return;
      // 这里可以添加提交逻辑
      getAddGuideShow(details.value).then((res) => {
        if (res.data.code === 0) {
          ElMessage({
            type: "success",
            message: res.data.result,
          });
          router.push("/road/equipmentParameters");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("表单校验失败");
      // 这里可以添加处理校验失败逻辑
    }
  } catch (error) {
    console.error("校验过程中发生错误:", error);
  }
};

// 循环遍历校验
const validateForms = async () => {
  let isValid = true;
  for (const ref of detailFormRefs.value) {
    // 使用 Promise 来等待 validate 的结果
    const valid = await new Promise((resolve) => {
      ref.validate((valid) => {
        resolve(valid);
      });
    });
    if (!valid) {
      isValid = false;
      break; // 如果有一个表单验证失败，可以立即停止后续验证
    }
  }
  return isValid;
};

// 取消
const resetForm = (formEl) => {
  if (!formEl) return;
  detailForm.data = {};
  formEl.resetFields();
  router.push("/road/equipmentParameters");
};

const list = ref({});

// 获取浏览器数据解密/调用回显数据接口
onMounted(async () => {
  console.log("route ===>", route);
  // 获取浏览器数据解密
  const encodedData = route.query.data;
  if (encodedData) {
    try {
      const decodedData = decodeURIComponent(encodedData);

      list.value = JSON.parse(decodedData);
      console.log("list ===>", list.value);
      await getRoadList("3").then((res) => {
        table.data = res.data.result;
      });
      console.log("table.data ===>", table.data);

      // 回显数据
      getGuideShowDetails(list.value.id).then((res) => {
        // console.log("res ===>", res);
        if (res.data.result.length != 0) {
          details.value = res.data.result;
          console.log("details.value ===>", details.value);

          // return
          let datalist = details.value;
          for (let i = 0; i < datalist.length; i++) {
            fileList.value[i].push({
              name: details.value[i].fileId,
              url: details.value[i].fileUrl,
            });
            let arrs = datalist[i].sections;
            let names = [];
            for (let n = 0; n < arrs.length; n++) {
              let name = getDateName(table.data, arrs[n]);
              names.push(name);
            }
            datalist[i].sectionsName = names;
          }
        } else {
          details.value = [
            {
              deviceId: "",
              type: "",
              // wordSize: "",
              // wordColor: "",
              // horizontal: "",
              // vertical: "",
              // sections: "",
              // parkingLots: "",
              // text: "",
              index: 0,
              fileId: "",
              fileUrl: "",
              xaxis: "",
              yaxis: "",
            },
          ];
        }
      });
    } catch (error) {
      console.error("Error parsing row data:", error);
    }
  }
  detailFormRefs.value = [];
});

const getDateName = (list, id) => {
  let result = "";
  if (list && id) {
    for (let i = 0; i < list.length; i++) {
      if (list[i].id === id) {
        result = list[i].name;
        break;
      }
    }
  }
  return result;
};

// 暴露方法
defineExpose({ submitForm });
</script>

<style lang="less" scoped>
.add-component {
  margin-top: 16px;
  min-height: 100%;
  background: #fff;
  border-radius: 6px;
  // overflow: auto;
}
.title {
  padding: 32px 32px 24px 32px;
  font-weight: 600;
  font-size: 18px;
  color: #333333;
}
.row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.content {
  padding: 0 32px 15px;
  border-bottom: 1px solid #e9e9e9;
}
.add-form {
  padding: 24px 32px 0;
}

.footer {
  padding: 32px;
  margin-bottom: 32px;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.reset-btn {
  width: 65px;
  height: 32px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
  font-weight: 400;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
.confirm-btn {
  width: 65px;
  height: 32px;
  background: #007aff;
  border-radius: 2px;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}
/deep/ .sections {
  /deep/ .el-form-item__label {
    display: flex !important;
    width: 187px !important;
  }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
